package com.bjpowernode.p2padmin.user.listener;

import com.bjpowernode.p2padmin.user.model.UserInfo;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Queue;

/**
 * ClassName:PermissionListener
 * Package:com.bjpowernode.p2padmin.user.listener
 * Description:TODO描述
 *
 * @date:2020/4/7 20:27
 * @author:CC
 */
public class PermissionListener implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfo user= (UserInfo) request.getSession().getAttribute("userSession");

        //用户没登录
        if (user==null){

            request.setAttribute("errorMessage","没有登录,请先登录");
            request.getRequestDispatcher("/noLogin").forward(request,response);
            return false;
        }

        //获取用户的请求路径
        String requestPath = request.getServletPath();

        StringBuilder requestParams= new StringBuilder("?");
        Map<String,String[]> paramsMap =request.getParameterMap();
        for (String key : paramsMap.keySet()) {
            requestParams.append(key);
            requestParams.append("=");
            requestParams.append(paramsMap.get(key)[0]);
            requestParams.append("&");
        }
        //删除参数数据中的最后一个字符
        requestParams.deleteCharAt(requestParams.length()-1);

        Map urlMap = user.getUrlMap();
        //请求路径中可能有的有参数 有的没有 ,因此只要进入if,无论有没有参数的请求路径
        // 在当前用户的权限map中都不存在

        if (!urlMap.containsKey(requestPath)&&!urlMap.containsKey(requestPath+requestParams)){

            request.setAttribute("errorMessage","对不起,您没有权限");
            request.setAttribute("helpMessage","请联系管理员");
            request.getRequestDispatcher("/noPermission").forward(request,response);

            return false;
        }

        return true;
    }


}
